package com.s59.rabc.commen;

        import com.fasterxml.jackson.core.json.JsonReadFeature;
        import com.fasterxml.jackson.databind.ObjectMapper;
        import com.s59.rabc.redis.RedisUtils;
        import lombok.SneakyThrows;
        import org.aspectj.lang.ProceedingJoinPoint;
        import org.aspectj.lang.annotation.Around;
        import org.aspectj.lang.annotation.Aspect;
        import org.aspectj.lang.reflect.MethodSignature;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Component;
        import org.springframework.util.StringUtils;
        import org.springframework.web.context.request.RequestContextHolder;
        import org.springframework.web.context.request.ServletRequestAttributes;

        import java.lang.reflect.Method;

@Aspect
@Component
public class RequiredPermsAspect {
    @Autowired
    private RedisUtils redisUtils;


    @Around(value = "@annotation(com.s59.rabc.commen.RequiredPerms)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        RequiredPerms annotation = methodSignature.getMethod().getDeclaredAnnotation(RequiredPerms.class);
        if(checkPerms(annotation.value())){
            return proceedingJoinPoint.proceed();
        }
        throw new AccessDeniedException("无权访问");
    }

    @SneakyThrows
    private boolean checkPerms(String value) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = servletRequestAttributes.getRequest().getHeader("token");
        String json = redisUtils.get(Constants.CACHE_PREFIX_TOKEN+token);
        if(StringUtils.hasText(json)){
            LoginUser loginUser = new ObjectMapper().readValue(json,LoginUser.class);
            return loginUser.getPermsList().contains(value);
        }
        return false;
    }

}
